import '@amap/amap-jsapi-types';
import { FC, useEffect, useRef, useState } from 'react';
import {
  useAddedMarkerList,
  useAddMarkerList,
  useRemoveMarkerList,
  useSetAddedMarkerList,
  useSetAddMarkerList,
  useSetRemoveMarkerList,
  useSetSingleAddMarker,
  useSetVideoCarNo,
  useSingleAddMarker,
  useVideoCarNo,
} from '@/store/realTimeMonitoringStore.ts';
import { useCatch, useMap } from '@/hooks';
import MapBasicTool from '@/components/Map/components/MapBasicTool.tsx';
import { getIconImg } from '@/components/Map/utils.ts';
import './style.css';
import { useTheme } from '@/store/settingsStore.ts';
import { ThemeMode, VideoFullScreenIcon } from '@ycx/ui';
import { useQuery } from '@tanstack/react-query';
import RealTimeMonitoringServices from '@/api/services/realTimeMonitoringServices.ts';
import { CarInfo } from '#/entity.ts';
import { Key } from 'antd/es/table/interface';
import CarInfoWrapper from '@/pages/realTimeMonitoring/compoents/CarInfoWrapper.tsx';
import { DescriptionsItemType } from 'antd/es/descriptions';
import VideoWrapper from '@/pages/realTimeMonitoring/compoents/VideoWrapper.tsx';
import ToolBar, { Tab } from '@/pages/realTimeMonitoring/compoents/ToolBar.tsx';
import { Tooltip } from 'antd';

type Props = {
  mapBasicTool?: boolean;
};

const IMap: FC<Props> = ({ mapBasicTool = true }) => {
  const theme = useTheme();
  const markerListRef = useRef<Map<Key, AMap.Marker>>(new Map());

  const [showModalCarNo, setShowModalCarNo] = useState<string>();
  const [infoItems, setInfoItems] = useState<DescriptionsItemType[]>([]);
  const [infoVisible, setInfoVisible] = useState(false);
  const catchFn = useCatch();

  // manage markers
  const addMarkerList = useAddMarkerList();
  const setAddMarkerList = useSetAddMarkerList();
  const addedMarkerList = useAddedMarkerList();
  const setAddedMarkerList = useSetAddedMarkerList();
  const setRemoveMarkerList = useSetRemoveMarkerList();
  const removeMarkerList = useRemoveMarkerList();
  const singleAddMarker = useSingleAddMarker();
  const setSingleAddMarker = useSetSingleAddMarker();

  // video
  const videoCarNo = useVideoCarNo();
  const setVideoCarNo = useSetVideoCarNo();

  const {
    mapInstance,
    zoomLevel,
    editLayer,
    addCustomMarker,
    // addCluster,
    changePitch,
    changeZoom,
  } = useMap({
    containerId: 'container',
    mapStyle: theme === ThemeMode.Light ? 'amap://styles/whitesmoke' : 'amap://styles/grey',
    center: [87.6177, 43.7928],
    // zoom: 5
  });

  const [activeKey, setActiveKey] = useState(1);

  const tabs: Tab[] = [
    { label: '视频模式', value: 0, toolKits: [] },
    { label: '地图模式', value: 1, toolKits: [] },
  ];

  const { data } = useQuery({
    queryKey: ['getCarRealTimeLocation', showModalCarNo],
    queryFn: () =>
      catchFn(() => RealTimeMonitoringServices.getCarRealTimeLocation({ carNo: showModalCarNo! })),
    select: ({ data }) => data,
    enabled: !!showModalCarNo,
    staleTime: 0,
  });

  const makeMarker = (item: CarInfo) => {
    const icon = new AMap.Icon({
      image: getIconImg(item.carStatus === 1 ? 'DRIVING' : 'OFFLINE'),
      imageSize: new AMap.Size(64, 64),
    });

    const marker = addCustomMarker({
      position: new AMap.LngLat(item.carTrackPartPo!.longitude, item.carTrackPartPo!.latitude!),
      icon: icon,
      anchor: 'center',
      clickable: true,
    });

    marker.setLabel({
      offset: new AMap.Pixel(0, -6),
      content: `<div class="icon-label ${item.carStatus === 1 ? 'driving' : 'offline'}">${item.carNo}</div>`,
      direction: 'bottom',
    });

    marker.on('click', function () {
      setShowModalCarNo(item.carNo);
      setInfoVisible(true);
    });

    markerListRef.current.set(item.carNo, marker);
  };

  // build info
  useEffect(() => {
    if (!data) return;

    setInfoItems([
      { key: 'company', label: '巡检队', children: '暂无', span: 24 },
      { key: 'lat', label: '经纬度', children: `${data.longitude}, ${data.latitude}`, span: 24 },
      { key: 'address', label: '地理位置', children: data.address ?? '暂无', span: 24 },
      { key: 'deviceTime', label: '位置时间', children: data.deviceTime ?? '暂无', span: 24 },
      { key: 'alarmDesc', label: '病害报警', children: data.alarmDesc ?? '暂无', span: 24 },
    ]);

    const isMarkerExist = markerListRef.current.get(data.carNo);

    if (isMarkerExist) isMarkerExist.setMap(null);

    makeMarker({
      carNo: videoCarNo?.carNo || singleAddMarker!.carNo,
      carStatus: videoCarNo?.carStatus || singleAddMarker!.carStatus,
      carTrackPartPo: {
        address: data.address,
        latitude: data.latitude,
        longitude: data.longitude,
        status: videoCarNo?.carStatus || singleAddMarker!.carStatus,
        deviceTime: data.deviceTime,
      },
    });

    if (activeKey === 1) {
      mapInstance.current?.setCenter([data.longitude, data.latitude!]);
      mapInstance.current?.setZoom(14);
    } else {
      const el = document.querySelector('.video-wrapper');
      mapInstance.current?.setFitView(
        undefined,
        false,
        [el?.clientHeight ?? 100, 100, (el?.clientWidth ?? 100) + 300, 100],
        14,
      );
    }

    setAddedMarkerList([...addedMarkerList, videoCarNo?.carNo || singleAddMarker!.carNo]);
    // setSingleAddMarker();
  }, [data, activeKey]);

  // checked multiple
  useEffect(() => {
    if (addMarkerList.length === 0) return;

    addMarkerList.forEach((i) => {
      makeMarker(i);
    });
    mapInstance.current?.setFitView(undefined, false, [100, 100, 100, 100], 14);

    setAddedMarkerList([...addedMarkerList, ...addMarkerList.map((item) => item.carNo)]);
    setAddMarkerList([]);
  }, [addMarkerList]);

  // unchecked: remove marker
  useEffect(() => {
    if (removeMarkerList.length === 0) return;

    removeMarkerList.forEach((carNo) => {
      const marker = markerListRef.current.get(carNo);
      marker?.setMap(null);
      markerListRef.current.delete(carNo);
      if (carNo === showModalCarNo) {
        setShowModalCarNo(undefined);
        setInfoVisible(false);
      }
    });

    setAddedMarkerList(addedMarkerList.filter((i) => !removeMarkerList.includes(i)));
    setRemoveMarkerList([]);
  }, [removeMarkerList]);

  // 单独 checked
  useEffect(() => {
    if (!singleAddMarker) return;
    setShowModalCarNo(singleAddMarker.carNo);
    setInfoVisible(true);
  }, [singleAddMarker]);

  useEffect(() => {
    if (!videoCarNo) return;

    setActiveKey(0);
    setSingleAddMarker(videoCarNo);
  }, [videoCarNo]);

  useEffect(() => {
    if (activeKey === 1) setVideoCarNo(undefined);
  }, [activeKey]);

  return (
    <div className="relative h-full">
      <div id="container" className="h-full" />
      <ToolBar tabs={tabs} activeKey={activeKey} onChange={setActiveKey}>
        {activeKey === 0 ? (
          <Tooltip title="视频全屏" placement="bottom">
            <div>
              <VideoFullScreenIcon
                style={{ color: 'var(--ycx-font-color-l2)', cursor: 'pointer', fontSize: '16px' }}
                onClick={() => {
                  const el = document.querySelector('video');
                  el?.requestFullscreen();
                }}
              />
            </div>
          </Tooltip>
        ) : null}
      </ToolBar>
      {mapBasicTool && (
        <MapBasicTool
          editLayer={editLayer}
          editPitch={changePitch}
          zoomLevel={zoomLevel}
          onChangeZoom={(isZoomIn) => {
            changeZoom(isZoomIn);
          }}
        />
      )}

      {infoVisible && (
        <CarInfoWrapper
          data={{ items: infoItems, carNo: showModalCarNo! }}
          onClose={() => setInfoVisible(false)}
          style={{
            left: activeKey === 1 ? '352px' : 'auto',
            right: activeKey === 0 ? '90px' : 'auto',
          }}
        />
      )}

      {activeKey === 0 && <VideoWrapper />}
    </div>
  );
};

export default IMap;
